package com.woyou.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.os.Environment;

/**
 * 打印日志类
 * @author zhou
 *
 */
public class PrintUncaughtException implements UncaughtExceptionHandler{

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		String info = null;
		ByteArrayOutputStream baos = null;
		PrintStream printStream = null;
		
		try {
			baos = new ByteArrayOutputStream();
			printStream = new PrintStream(baos);
			ex.printStackTrace(printStream);
			byte[] data = baos.toByteArray();
			info = new String(data);
			data = null;
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (printStream != null) {
					printStream.close();
				}
				if (baos != null) {
					baos.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		writeErrorLog(info);
	}
	
	/**
	 * 向文件中写入错误信息
	 * 
	 * @paraminfo
	 */
	protected void writeErrorLog(String info) {
		String DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ideliver/log/";
		String NAME = getCurrentDateString() + ".txt";
		//判断是否有sd卡
		if(isSDCARDMounted()){
			//删除文件夹及文件
			//FileUtils.delDir(DIR);
			File dir = new File(DIR);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			File file = new File(dir, NAME);
			try {
				FileOutputStream fileOutputStream = new FileOutputStream(file, true);
				fileOutputStream.write(info.getBytes());
				fileOutputStream.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 获取当前日期
	 * 
	 * @return
	 */
	private static String getCurrentDateString() {
		String result = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault());
		Date nowDate = new Date();
		result = sdf.format(nowDate);
		return result;
	}
	
	/**
	 * 判断是否存在sd卡
	 * @return
	 */
	public static boolean isSDCARDMounted() {
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED))
			return true;
		return false;
	}
	
}
